package com.wingice.exception;

import com.wingice.common.exception.ParameterValidateException;
import com.wingice.common.web.ResultBean;
import com.wingice.quartz.exception.KnifeQuartzException;
import com.wingice.spring.security.exception.KnifeAuthenticationException;
import com.wingice.system.exception.SysBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotNull;


/**
 * @author 胡昊
 * Description: 统一异常拦截器
 * Date: 2019/3/10
 * Time: 20:33
 * Create: DoubleH
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SysBusinessException.class)
    @ResponseBody
    public ResultBean<String> sysBusinessExceptionHandler(SysBusinessException e) {
        log.error(e.getMsg(), e);
        return ResultBean.restResult(null, e.getCode(), e.getMsg(), e.getErrorMsg());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResultBean<String> businessExceptionHandler(BusinessException e) {
        log.error(e.getMsg(), e);
        return ResultBean.restResult(null, e.getCode(), e.getMsg(), e.getErrorMsg());
    }

    @ExceptionHandler(com.wingice.common.exception.BusinessException.class)
    @ResponseBody
    public ResultBean<String> commonBusinessExceptionHandler(com.wingice.common.exception.BusinessException e) {
        log.error(e.getMsg(), e);
        return ResultBean.restResult(null, e.getCode(), e.getMsg(), e.getErrorMsg());
    }

    @ExceptionHandler(ParameterValidateException.class)
    @ResponseBody
    public ResultBean<Object> parameterValidateExceptionHandler(@NotNull ParameterValidateException e) {
        return ResultBean.restResult(null, e.getCode(), e.getMsg());
    }

    @ExceptionHandler(BadCredentialsException.class)
    @ResponseBody
    public ResultBean<String> badCredentialsExceptionHandler(BadCredentialsException e) {
        return ResultBean.restResult(null, 500, "用户名密码错误", e.getMessage());
    }

    @ExceptionHandler(KnifeAuthenticationException.class)
    @ResponseBody
    public ResultBean<String> knifeAuthenticationExceptionHandler(KnifeAuthenticationException e) {
        return ResultBean.restResult(null, e.getCode(), e.getMessage(), e.getMessage());
    }

    @ExceptionHandler(KnifeQuartzException.class)
    @ResponseBody
    public ResultBean<String> knifeQuartzExceptionHandler(KnifeQuartzException e) {
        return ResultBean.restResult(null, 500, e.getMessage(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultBean<Object> exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return ResultBean.restResult(null, 500, "服务器可能睡着啦，请稍后再试", e.getMessage());
    }
}
